<template>
  <div class="scanner-container">
    <h3 class="title">扫描结果：</h3>
    <div class="result-box" :class="{ 'empty': !scannedCode }">
      {{ scannedCode || '请使用扫码枪进行扫描' }}
    </div>
    <div v-if="showDebug" class="debug-info">
      <p>最近按键：{{ lastKey }}</p>
      <p>输入间隔：{{ lastInterval }}ms</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScannerComponent',
  data () {
    return {
      scannedCode: '',
      rawInputBuffer: [],
      inputTimer: null,
      lastScanTime: null,
      lastKey: '',
      lastInterval: 0,
      SCAN_TIMEOUT: 100,
      AUTO_COMMIT_TIME: 500,
      debugMode: true
    }
  },
  computed: {
    showDebug () {
      return this.debugMode
    }
  },
  mounted () {
    window.addEventListener('keydown', this.handleKeyDown)
    window.addEventListener('keyup', this.handleKeyUp)
  },
  beforeDestroy () {
    window.removeEventListener('keydown', this.handleKeyDown)
    window.removeEventListener('keyup', this.handleKeyUp)
  },
  methods: {
    handleKeyDown (e) {
      if (e.ctrlKey || e.altKey || e.metaKey) return

      const currentKey = e.key
      const currentTime = Date.now()

      this.lastKey = currentKey
      this.lastInterval = this.lastScanTime ? currentTime - this.lastScanTime : 0

      if (this.isControlKey(currentKey)) {
        if (['Enter', 'Tab'].includes(currentKey)) {
          this.commitScan()
          e.preventDefault()
        }
        return
      }

      if (this.checkInputInterval(currentTime)) {
        this.resetScanner()
      }

      this.processCharacter(currentKey, currentTime, e)
    },
    handleKeyUp () {
      clearTimeout(this.inputTimer)
      this.inputTimer = setTimeout(() => {
        if (this.rawInputBuffer.length > 0) {
          this.commitScan()
        }
      }, this.AUTO_COMMIT_TIME)
    },
    commitScan () {
      const rawData = this.rawInputBuffer.join('')
      this.scannedCode = this.cleanScannerData(rawData)
      console.log('清洗结果:', this.scannedCode)
      this.resetScanner()
    },
    cleanScannerData (raw) {
      // 步骤1：去除首尾非字母数字字符
      let cleaned = raw
        .replace(/^[^\dA-Za-z]+/g, '')
        .replace(/[^\dA-Za-z]+$/g, '')

      // 步骤2：智能识别并提取URL部分
      const urlPattern = /https?:\/\/[^\s]+/i
      const urlMatch = cleaned.match(urlPattern)

      return urlMatch ? urlMatch[0] : cleaned
    },
    resetScanner () {
      clearTimeout(this.inputTimer)
      this.rawInputBuffer = []
      this.lastScanTime = null
    },
    isControlKey (key) {
      return ['Control', 'Alt', 'Shift', 'Enter', 'Tab', 'Clear', 'Escape', 'CapsLock', 'NumLock'].includes(key)
    },
    checkInputInterval (currentTime) {
      return this.lastScanTime && (currentTime - this.lastScanTime) > this.SCAN_TIMEOUT
    },
    processCharacter (char, timestamp, event) {
      if (!event.repeat) {
        this.rawInputBuffer.push(char)
      }
      this.lastScanTime = timestamp
    }
  }
}
</script>

<style scoped>
.scanner-container {
  max-width: 600px;
  margin: 2rem auto;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.title {
  color: #2c3e50;
  margin-bottom: 1rem;
}

.result-box {
  padding: 1.5rem;
  font-size: 1.1rem;
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  min-height: 60px;
  transition: border-color 0.3s ease;
}

.result-box.empty {
  border-color: #a0a0a0;
  color: #757575;
}

.debug-info {
  margin-top: 1rem;
  padding: 1rem;
  background: #fff3cd;
  border-radius: 4px;
  font-size: 0.9rem;
}

</style>
